/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package JavaFiler;

/**
 *
 * @author Per Stian Hoff & Gjerde
 */
import java.io.IOException;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Named("user") // or @ManagedBean(name="user")
@SessionScoped

public class UserBean implements Serializable {

    private String name;
    private ArrayList<User> users;
    private User newUser = new User();
    dbConnection dbCon = new dbConnection();
    private boolean checkOkUser = false;
    //private boolean checkNew
    private boolean checkNotUser = true;
    private int indexOfNewRow = -1;
    private User editUser = null;
    private User copy = null;
    private boolean newRow = false;

    //Gets the userdata from the current logged inn user
    private void getUserData() {
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
        Object requestObject = context.getRequest();
        if (!(requestObject instanceof HttpServletRequest)) {
            return;
        }
        HttpServletRequest request = (HttpServletRequest) requestObject;
        name = request.getRemoteUser();
    }

    public String getUsername() {
        if (name == null) {
            getUserData();
        }
        return name == null ? "" : name;
    }
    public String getName(){
        return name;
    }

    public void setName(String name){
        this.name = name;
    }

    //Checks if you are logged in.
    public Boolean getCheckLogin() {
        if (getUsername().equals("") == false) {
            return false;
        }
        return true;
    }
    //Used when you log out.
    public void logout() throws IOException {
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
        Object requestObject = context.getRequest();
        HttpServletRequest request = (HttpServletRequest) requestObject;
        HttpServletResponse response = (HttpServletResponse) context.getResponse();
        HttpSession session = (HttpSession) context.getSession(false);
        session.invalidate();
        request.getSession().invalidate();
        response.sendRedirect("../faces/index.xhtml");
    }
    //Finds the role of the current logged in user.
    public Boolean findRole() {
        boolean check = false;
        if (getRole().equals("system")) {
            check = true;
        }
        return check;
    }

    public String getRole() {

        return isInRole("bruker") ? "bruker" : "system";
    }

    public boolean isInRole(String role) {
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
        Object requestObject = context.getRequest();
        if (!(requestObject instanceof HttpServletRequest)) {
            return false;
        }
        HttpServletRequest request = (HttpServletRequest) requestObject;
        return request.isUserInRole(role);
    }
    //Puts all the students from the current logged in user.
    public ArrayList<User> getTableUsers() throws SQLException {
        if (users == null) {
            users = new ArrayList<User>();
        }
        getAllUsers();
        return users;
    }

    synchronized private void getAllUsers() throws SQLException {
        //dbConnection connectionClass = new dbConnection();
        Connection connection = dbCon.getCon();
        users.clear();
        try {
            //prep = dbCon.getCon().prepareStatement("SELECT * FROM bruker b ,rolle r WHERE b.brukernavn=r.brukernavn");
            PreparedStatement prep = connection.prepareStatement("SELECT * FROM bruker b, rolle r, elev e WHERE (b.brukernavn=r.brukernavn)"
                    + " AND (r.brukernavn = e.brukernavn) AND (e.lererbrukernavn = ?)");
            prep.setString(1, name);
            ResultSet res = prep.executeQuery();
            try {

                while (res.next()) {
                    users.add(
                            new User(
                            res.getString("brukernavn"),
                            res.getString("passord"),
                            res.getString("navn"),
                            res.getString("rolle")));
                }
                res.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }


        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbCon.disconnect();
        }
    }

    public void setNewUser(User newUser) {
        this.newUser = newUser;
    }

    public User getNewUser() {
        return newUser;
    }
    //Adds a new user.
     public void addNewUser(User newUser) {
        checkOkUser = false;
        PreparedStatement userTable = null;
        PreparedStatement roleTable = null;
        PreparedStatement GameStatsTable = null;
        try {
            int userAdded = -1;
            int RoleAdded = -1;
            int teacherAdded = -1;
            int studentAdded = -1;
            int GameStatsAdded = -1;
            //Adds User
            userTable = dbCon.getCon().prepareStatement("INSERT INTO bruker(brukernavn,passord,navn) VALUES (?, ?, ?)");
            userTable.setString(1, newUser.getUsername());
            userTable.setString(2, newUser.getPassword());
            userTable.setString(3, newUser.getName());
            userAdded = userTable.executeUpdate();
            userTable.close();
            //Adds role
            roleTable = dbCon.getCon().prepareStatement("INSERT INTO rolle(brukernavn,rolle) VALUES(?, ?)");
            roleTable.setString(1, newUser.getUsername());
            roleTable.setString(2, newUser.getRole());
            RoleAdded = roleTable.executeUpdate();
            roleTable.close();
             //Adds Game Stats
            GameStatsTable = dbCon.getCon().prepareStatement("INSERT INTO spillarkiv(brukernavn, forsok_pluss, pluss_score, forsok_minus, minus_score, forsok_gange, gange_score, forsok_deling, deling_score)values(?,?,?,?,?,?,?,?,?)");
            GameStatsTable.setString(1, newUser.getUsername());
            GameStatsTable.setInt(2, 0);
            GameStatsTable.setInt(3, 0);
            GameStatsTable.setInt(4, 0);
            GameStatsTable.setInt(5, 0);
            GameStatsTable.setInt(6, 0);
            GameStatsTable.setInt(7, 0);
            GameStatsTable.setInt(8, 0);
            GameStatsTable.setInt(9, 0);
            GameStatsAdded = GameStatsTable.executeUpdate();
            GameStatsTable.close();
            String role = newUser.getRole().toLowerCase().trim();
            if (role.equals("system")) {
                //Adds teacher
                PreparedStatement teacherTable = null;
                teacherTable = dbCon.getCon().prepareStatement("INSERT INTO lerer(brukernavn) VALUES(?)");
                teacherTable.setString(1, newUser.getUsername());
                teacherAdded = teacherTable.executeUpdate();
                studentAdded = 1;
                teacherTable.close();
            } else if (role.equals("bruker")) {
                //Adds student
                PreparedStatement studentTable = null;
                studentTable = dbCon.getCon().prepareStatement("INSERT INTO elev(brukernavn, lererbrukernavn) VALUES(?,?)");
                studentTable.setString(1, newUser.getUsername());
                //getBrukernavn();
                studentTable.setString(2, name);
                studentAdded = studentTable.executeUpdate();
                teacherAdded = 1;
                studentTable.close();
            }
            
            
            if (RoleAdded == 1 && userAdded == 1 && studentAdded == 1 && teacherAdded == 1 && GameStatsAdded == 1) {
                this.checkOkUser = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbCon.disconnect();
        }
    }
    public boolean getCheckUserAdded(){
        return checkOkUser;
    }
    //Used when changing a user.
    public String changeUser(User edit) {
        //newUser = edit;
        copy = new User(
                edit.getUsername(),
                edit.getPassword(),
                edit.getName(),
                edit.getRole());

        indexOfNewRow = users.indexOf(edit);  // NB! the equals() method is used
        return null;
    }
    //Gets the row from datatable that the user is working on.
    public boolean getWorkingWithNewRow() {
        return indexOfNewRow >= 0;
    }
    public boolean newRow(User row) {
        return (users.indexOf(row) == indexOfNewRow); // NB! the equals() method is used
    }

    public User getEditUser() {
        editUser = users.get(indexOfNewRow);
        return editUser;
    }

    public void setEditUser(User editUser) {
        this.editUser = editUser;
    }
    //Confirms the new data from the user and edit them.
    public void confirmInsert() throws SQLException {
        deleteUser(copy);
        addNewUser(editUser);
        copy = null;
        editUser = null;
        getTableUsers();
        indexOfNewRow = -1;
    }

    public void noEdit(User n) {
        System.out.println(copy);
            users.remove(0);
            copy = null;
            editUser = null;
            indexOfNewRow = -1;
    }
    //delete choosen user
    public String deleteUser(User delete) throws SQLException {
        int updateStudent = -1;
        int updateRole = -1;
        int updateUser = -1;
        int updateGameStats = -1;
        try {
            PreparedStatement deleteStatementStudent = dbCon.getCon().prepareStatement("DELETE FROM elev WHERE brukernavn = ?");
            deleteStatementStudent.setString(1, delete.getUsername());
            updateStudent = deleteStatementStudent.executeUpdate();
            deleteStatementStudent.close();

            PreparedStatement deleteStatementRole = dbCon.getCon().prepareStatement("DELETE FROM rolle WHERE brukernavn = ?");
            deleteStatementRole.setString(1, delete.getUsername());
            updateRole = deleteStatementRole.executeUpdate();
            deleteStatementRole.close();

            PreparedStatement deleteStatementUser = dbCon.getCon().prepareStatement("DELETE FROM bruker WHERE brukernavn = ?");
            deleteStatementUser.setString(1, delete.getUsername());
            updateUser = deleteStatementUser.executeUpdate();
            deleteStatementUser.close();

            PreparedStatement deleteStatementGameStats = dbCon.getCon().prepareStatement("DELETE FROM spillarkiv WHERE brukernavn = ?");
            deleteStatementGameStats.setString(1, delete.getUsername());
            updateGameStats = deleteStatementGameStats.executeUpdate();
            deleteStatementGameStats.close();
            
            users.remove(delete);

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbCon.disconnect();
        }
        getTableUsers();
        return null;
    }
}